package com.valveinspectionsys.routing.activity;

import java.io.IOException;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;

import com.valveinspectionsys.R;
import com.valveinspectionsys.dbhelp.XmlNameHelper;
import com.valveinspectionsys.povo.DeviceVo;
import com.valveinspectionsys.routing.db.DeviceRoutingDao;
import com.valveinspectionsys.util.CHexConver;
import com.valveinspectionsys.util.DateUtil;
import com.valveinspectionsys.util.SharedPreferenceUtil;
import com.valveinspectionsys.util.TipHelper;

import android.app.Activity;
import android.app.Dialog;
import android.app.PendingIntent;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.IntentFilter.MalformedMimeTypeException;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.MifareClassic;
import android.nfc.tech.NfcV;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 设备绑定RFID编号
 * @author King
 * 2013-4-26
 */
public class DeviceBandingActivity extends Activity implements OnClickListener,BDLocationListener {
    public TextView textview1;//设备名称
    public TextView textview2;//设备编号
    public TextView textview3;//设备地址
    public TextView textview4;//RFID编号
    public TextView textview5;//纬度
    public TextView textview6;//经度
    
    public Button button1;//一键绑定
    public Button button2;//保存
    public DeviceRoutingDao dao;
    public SharedPreferenceUtil sp;
    
    public DeviceVo device;
    
    public String deviceid;
    
    private NfcAdapter mAdapter;
    private PendingIntent mPendingIntent;
    private IntentFilter[] mFilters;
    private String[][] mTechLists;
 
    private boolean isNfc=false;
    private String RFID;
    private long time;
    
    private LocationClient client;
    private Double  latitude;
    private Double  longitude;
    public Dialog dialog = null;
    
    public boolean isSave=false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
	
	super.onCreate(savedInstanceState);
	setContentView(R.layout.device_banding);
	Intent intent=getIntent();
	deviceid=intent.getStringExtra("deviceid");
	sp=new SharedPreferenceUtil(this);
	dao=new DeviceRoutingDao(this, sp.getValue(XmlNameHelper.SqliteName));
	init();
	initDate();
	initlocation();
	mAdapter = NfcAdapter.getDefaultAdapter(DeviceBandingActivity.this);
	mPendingIntent = PendingIntent.getActivity(DeviceBandingActivity.this, 0, new Intent(DeviceBandingActivity.this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
	IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
	try {
	    ndef.addDataType("*/*");
	    mFilters = new IntentFilter[] { ndef, };
	    mTechLists = new String[][] { new String[] { NfcV.class.getName() }, new String[] { MifareClassic.class.getName() } };

	} catch (MalformedMimeTypeException e) {
	    // TODO Auto-generated catch block
	    e.printStackTrace();
	}
    }

    //初始化控件
    public void init(){
	textview1=(TextView)findViewById(R.id.waterbanding_username);
	textview2=(TextView)findViewById(R.id.waterbanding_waternumber);
	textview3=(TextView)findViewById(R.id.waterbanding_wateradds);
	textview4=(TextView)findViewById(R.id.waterbanding_RFID);
	textview5=(TextView)findViewById(R.id.waterbanding_latitude);
	textview6=(TextView)findViewById(R.id.waterbanding_longitude);
	button1=(Button)findViewById(R.id.waterbanding_readcard);
	button2=(Button)findViewById(R.id.waterbanding_button);
	button1.setOnClickListener(this);
	button2.setOnClickListener(this);
	
    }
    //初始化数据
    public void initDate(){
	device=dao.queryRfidDevice(null,deviceid , null);
	if(device!=null){
	    textview1.setText(device.getUseStatus());
	    textview2.setText(device.getDeviceNumber());
	    textview3.setText(device.getDeviceAdds());
	    textview4.setText(device.getRfidNumber());
	    textview5.setText("纬度:"+device.getLatitude());
	    textview6.setText("维度:"+device.getLongitude());
	    
	}
    }
    
    
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
	if(keyCode==KeyEvent.KEYCODE_BACK){
	    setResult(RESULT_OK);
	    finish();
	}
	return super.onKeyDown(keyCode, event);
    }
    
    
    
   
    @Override
    public void onClick(View v) {
	switch (v.getId()) {
	case R.id.waterbanding_readcard:
	       isNfc=true;
	       Toast.makeText(DeviceBandingActivity.this, "读卡中请将终端靠近标签", Toast.LENGTH_SHORT).show();
	       RFID="";
	       time=System.currentTimeMillis();
	       new Thread(){

		@Override
		public void run() {
		          while(isNfc){
		              if(!TextUtils.isEmpty(RFID)){
		        	  Message msg=myHandler.obtainMessage();
		        	  msg.what=1;
		        	  myHandler.sendMessage(msg);
		        	  isNfc=false;
		              }
		              if(System.currentTimeMillis()-time>10000){
		        	  Message msg=myHandler.obtainMessage();
		        	  msg.what=2;
		        	  myHandler.sendMessage(msg);
		        	  isNfc=false;
		              }
		              try {
				Thread.sleep(300);
			    } catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			    }
		          }
		    super.run();
		}
		   
	       }.start();
	    break;

	default:
	    break;
	}
	
    }

    
    @Override
    protected void onPause() {

	mAdapter.disableForegroundDispatch(this);

	super.onPause();
    }

    @Override
    protected void onResume() {
	mAdapter.enableForegroundDispatch(this, mPendingIntent, mFilters, mTechLists);

	super.onResume();
    }

    @Override
    protected void onNewIntent(Intent intent) {
	if (!isNfc) {
	    return;
	}

	if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction())) {
	    Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
	    for (String tech : tagFromIntent.getTechList()) {
		System.out.println(tech);
	    }
	    time = System.currentTimeMillis();
	    MifareClassic mf = MifareClassic.get(tagFromIntent);
	    if (mf != null) {

		boolean auth = false;
		try {
		    mf.connect();
		    auth = mf.authenticateSectorWithKeyA(0, MifareClassic.KEY_DEFAULT);// 获取第一个扇区权限
		    if (auth) {
			byte[] date = mf.readBlock(0);// 读取block 0
			RFID = CHexConver.bytesToHexStrings(date);
			Message msg = myHandler.obtainMessage();
			msg.what = 1;
			msg.obj = RFID;
			myHandler.sendMessage(msg);
		    }

		} catch (IOException e) {

		    e.printStackTrace();
		} finally {
		    try {
			mf.close();
		    } catch (IOException e) {

			e.printStackTrace();
		    }
		}

	    }
	    NfcV nf = NfcV.get(tagFromIntent);
	    if (nf != null) {
		RFID = CHexConver.bytesToHexStrings(nf.getTag().getId());
		Message msg = myHandler.obtainMessage();
		msg.what = 1;
		msg.obj = RFID;
		myHandler.sendMessage(msg);
	    }

	}

	super.onNewIntent(intent);
    }

     Handler myHandler=new Handler(){

	@Override
	public void handleMessage(Message msg) {
	    if(msg.what==1){
		DeviceVo d=dao.queryRfidDevice(RFID, null, null);
		if(d==null){
		    if(client!=null&&!client.isStarted()){
			client.start();
		    }
		    textview4.setText(RFID);
		}else{
		    Toast.makeText(DeviceBandingActivity.this, "此标签已绑定过不能再绑定", Toast.LENGTH_SHORT).show();
		}
	    }else if(msg.what==2){
		Toast.makeText(DeviceBandingActivity.this, "读卡超时", Toast.LENGTH_SHORT).show();
	    }
	    super.handleMessage(msg);
	}
	 
     };
     
     /**
      * 初始化定位
      */
     public void initlocation() {

 	client = new LocationClient(this);
 	LocationClientOption option = new LocationClientOption();
 	// 打开GPS
 	option.setOpenGps(true);

 	// 设置坐标类型
 	option.setCoorType("bd09ll");

 	// 设置网络优先

 	option.setPriority(LocationClientOption.GpsFirst);

 	// 设置产品线名称
 	option.setProdName("waterSys");
 	option.disableCache(true);// 禁止启用缓存定位
 	// 设置定位定时时间
 	option.setScanSpan(10000);
 	client.setLocOption(option);
 	client.registerLocationListener(this);

     }
   

    @Override
    public void onReceiveLocation(BDLocation location) {
	GPS(location);
	
    }

    @Override
    public void onReceivePoi(BDLocation arg0) {
	// TODO Auto-generated method stub
	
    }
    
    /**
     * 得到定位数据
     * 
     * @param location
     */
    public void GPS(BDLocation location) {

	if (location != null) {

	    if (location.getLocType() == 61) {
		client.stop();
		textview6.setText("纬度:" + location.getLatitude());
		textview5.setText("经度：" + location.getLongitude());
		latitude = location.getLatitude();
		longitude = location.getLongitude();

		showMessage("定位成功");
		TipHelper.Vibrate(this, 1000);
		sp.insertValue(XmlNameHelper.GPSLATITUDE, location.getLatitude() + "");
		sp.insertValue(XmlNameHelper.GPSLONGITUDE, location.getLongitude() + "");
		sp.insertValue(XmlNameHelper.GPSDATE, System.currentTimeMillis() + "");
		banding();

	    } else {

		client.stop();
		showDialog();
		TipHelper.Vibrate(this, 1000);

	    }
	} else {
	    client.stop();
	    showDialog();
	    TipHelper.Vibrate(this, 1000);
	}
    }
    public boolean banding(){
	boolean b=dao.insertDeviceBanding(deviceid, RFID, latitude, longitude);
	System.out.println("---------绑定状态------"+b);
	return b;
	
    }
    
    public void showDialog() {

	String message = "";
	if (sp.getValue(XmlNameHelper.GPSDATE).equals("0")) {
	    message = "还没有定位成功过！";
	} else {
	    long ti = System.currentTimeMillis() - Long.parseLong(sp.getValue(XmlNameHelper.GPSDATE));

	    message = "最近一次定位时间在:" + DateUtil.getMuntion(ti);
	}

	Builder builder = new android.app.AlertDialog.Builder(this);
	// 设置对话框的图标
	builder.setIcon(R.drawable.buttondraw);
	// 设置对话框的标题

	builder.setMessage(message);

	// 添加一个确定按钮
	builder.setPositiveButton(" 确 定 ", new DialogInterface.OnClickListener() {
	    public void onClick(DialogInterface dialog, int which) {
		textview6.setText("纬度:" + sp.getValue(XmlNameHelper.GPSLATITUDE));
		textview5.setText("经度：" + sp.getValue(XmlNameHelper.GPSLONGITUDE));
		latitude = Double.parseDouble(sp.getValue(XmlNameHelper.GPSLATITUDE));
		longitude = Double.parseDouble(sp.getValue(XmlNameHelper.GPSLONGITUDE));
		banding();
		dialog.dismiss();
	    }
	});
	builder.setNeutralButton("取消", new DialogInterface.OnClickListener() {

	    @Override
	    public void onClick(DialogInterface dialog, int which) {
		textview6.setText("纬度:" + 0.0);
		textview5.setText("经度：" + 0.0);
		latitude = 0.0;
		longitude = 0.0;
		banding();
		dialog.dismiss();

	    }
	});
	// 创建一个单选按钮对话框
	dialog = builder.create();
	dialog.show();

    }
    // 提示消息
    public void showMessage(String message) {
	Toast toast = Toast.makeText(this, message, Toast.LENGTH_SHORT);
	toast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 200);
	toast.show();
    }
    
  
    @Override
    protected void onDestroy() {
	dao.close();
	if(client!=null&&client.isStarted()){
	    client.stop();
	}
	super.onDestroy();
    }

   
}
